//
//  VPOSPhotoButton.m
//  Colourful
//
//  Created by xy on 13-7-23.
//  Copyright (c) 2013年 handpay. All rights reserved.
//

#import "ZZTongPhotoButton.h"
#import "CategoryUtil.h"
#import "DefineUtil.h"
#include "CUtility.h"
#import "Utility.h"

@interface ZZTongPhotoButton ()
@property(nonatomic, retain)UILabel* tagLabel;
@property(nonatomic, retain)UILabel* msgLabel;
@property(nonatomic, retain)UIImageView* tagImageView;
@property(nonatomic, retain)UIView* noPhotoView;
@property(nonatomic, retain)UIView* havePhotoView;
@property(nonatomic, retain)UIButton* openCameraButton;
@property(nonatomic, retain)NSString* defaultImageName;
@property(nonatomic, retain)UIActivityIndicatorView* loadView;
@property(nonatomic, retain)UIImage* helpImage;

@property(nonatomic) BOOL isShotPhoto;
@end

@implementation ZZTongPhotoButton
@synthesize delegate;
@synthesize presentScreen;

#define kClearButtonTag  10001

- (void)doOpenCamera:(UIButton*)button{
    if ([self.delegate respondsToSelector:@selector(photoStart:)]) {
        [self.delegate photoStart:self];
    }
    
    UIImagePickerController* pickerView = [[UIImagePickerController alloc] init];
    pickerView.sourceType = UIImagePickerControllerSourceTypeCamera;
    pickerView.videoQuality = UIImagePickerControllerQualityTypeLow;
    pickerView.delegate = self;
    [self.presentScreen presentViewController:pickerView animated:YES completion:nil];
    [pickerView release];
}

- (void)buttonClick{
    if (self.noPhotoView.hidden && self.photoImageView.image) {
        [self scaleAnimations:self.photoImageView.image];
    }
//    else{
//        if (self.buttonStatus == PhotoStatusSuccess) {
//            return;
//        }
//        [self doOpenCamera];
//    }
}

- (void)scaleAnimations:(UIImage*)image{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    
    
    CGFloat windowWidth = window.frame.size.width;
    UIView* tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, windowWidth, window.frame.size.height)];
    tempView.backgroundColor = UIColorFromRGBA(0x000000, 0.5);
    
    
    UIImageView *imgView = [[UIImageView alloc] initWithImage:image];
    CGFloat rate = image.size.width / self.frame.size.width;
    CGFloat imgHeight = image.size.height / rate;
    
    CGRect makeFrame = CGRectMake(window.center.x - self.frame.size.width / 2, window.center.y - imgHeight / 2, self.frame.size.width, imgHeight);
    imgView.frame = makeFrame;
    [tempView addSubview:imgView];
    
    
    UIButton* tempButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tempButton setImage:[UIImage imageNamed:@"closebig.png"] forState:UIControlStateNormal];
    tempButton.frame = CGRectMake(0, 0, 58, 58);
    tempButton.center = CGPointMake(windowWidth / 2, window.frame.size.height * 4 / 5);
    [tempButton addTarget:self action:@selector(closeButtonClick:) forControlEvents:UIControlEventTouchDown];
    [tempView addSubview:tempButton];
    
    [window addSubview:tempView];
    
    [UIView beginAnimations:@"frameChange" context:nil];
    [UIView setAnimationDuration:0.5];
    
    rate = windowWidth / makeFrame.size.width;
    
    imgView.transform = CGAffineTransformMakeScale(rate, rate);
    [UIView commitAnimations];
    
    [imgView release];
    [tempView release];
}

- (void)closeButtonClick:(UIButton *)button{
    [button.superview removeFromSuperview];
}

- (void)initialize{
    [self addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    
//    [self setBackgroundImage:[UIImage imageNamed:@"whitebutton.png"] forState:UIControlStateNormal];
    [self setBackgroundColor:[UIColor whiteColor]];
    
    UIFont *normalFont = [UIFont systemFontOfSize:12];
    
    UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 20, 5, 16)];
    tempLabel.text = @"*";
    tempLabel.textColor = [UIColor redColor];
    tempLabel.font = normalFont;
    self.tagLabel = tempLabel;
    [tempLabel release];
    [self addSubview:self.tagLabel];
    
    
    tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 20, self.frame.size.width, 16)];
    tempLabel.textColor = [UIColor blackColor];
    tempLabel.textAlignment = NSTextAlignmentCenter;
    tempLabel.font = normalFont;
    self.msgLabel = tempLabel;
    [tempLabel release];
    [self addSubview:self.msgLabel];
    
    
    [self createNoPhotoView];
    [self createHavePhotoView];
    
    UIButton *upButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *upImage = [UIImage imageNamed:@"up.png"];
    upButton.frame = CGRectMake(0, 0, upImage.size.width * 2, upImage.size.height * 2);
    [upButton setImage:upImage forState:UIControlStateNormal];
    [upButton setImageEdgeInsets:UIEdgeInsetsMake(-upImage.size.height / 2, -upImage.size.width / 2, 0, 0)];
    [upButton addTarget:self action:@selector(doOpenCamera:) forControlEvents:UIControlEventTouchUpInside];
//    [upButton setBackgroundColor:[UIColor redColor]];
    self.openCameraButton = upButton;
    [self addSubview:self.openCameraButton];
    
    self.isShotPhoto = NO;
}

- (void)createNoPhotoView{
    UIView* tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    tempView.backgroundColor = [UIColor clearColor];
    self.noPhotoView = tempView;
    [tempView release];
    
    [self addSubview:self.noPhotoView];
    
    UIImage *helpImage = [UIImage imageNamed:@"question.png"];
    CGSize imageSize = helpImage.size;
    UIButton* helpButton = [UIButton buttonWithType:UIButtonTypeCustom];
    helpButton.frame = CGRectMake(self.frame.size.width - 2 - imageSize.width, 2, imageSize.width, imageSize.height);
    [helpButton setImage:helpImage forState:UIControlStateNormal];
    [helpButton addTarget:self action:@selector(helpButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.noPhotoView addSubview:helpButton];
    
    UIImageView *tempImageView = [[UIImageView alloc] init];
    self.tagImageView = tempImageView;
    [tempImageView release];
    [self.noPhotoView addSubview:self.tagImageView];
}

- (void)createHavePhotoView{
    UIView* tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    tempView.backgroundColor = [UIColor clearColor];
    self.havePhotoView = tempView;
    [tempView release];
    
    [self addSubview:self.havePhotoView];
    self.havePhotoView.hidden = YES;
    
    UIImage *clearImage = [UIImage imageNamed:@"clear.png"];
    CGSize imageSize = clearImage.size;
    UIButton* clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
    clearButton.tag = kClearButtonTag;
    clearButton.frame = CGRectMake(self.frame.size.width - 2 - imageSize.width, 2, imageSize.width, imageSize.height);
    [clearButton setImage:clearImage forState:UIControlStateNormal];
    [clearButton addTarget:self action:@selector(clearClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.havePhotoView addSubview:clearButton];
    
    UIImageView *tempImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 60)];
    tempImageView.center = CGPointMake(self.havePhotoView.frame.size.width / 2, self.havePhotoView.frame.size.height / 2 - 10);
    self.photoImageView = tempImageView;
    [tempImageView release];
    [self.havePhotoView addSubview:self.photoImageView];
}

- (void)helpButtonClick:(UIButton*)button{
    if (self.helpImage) {
        [self scaleAnimations:self.helpImage];
    }
}

- (void)clearClick:(UIButton*)button{
    self.havePhotoView.hidden = YES;
    self.noPhotoView.hidden = NO;
    
    UIButton* clearButton = (UIButton*)[self.havePhotoView viewWithTag:kClearButtonTag];
    [clearButton setImage:[UIImage imageNamed:@"clear.png"] forState:UIControlStateNormal];
    clearButton.userInteractionEnabled = YES;
    self.openCameraButton.hidden = NO;
    self.tagImageView.image = [UIImage imageNamed:self.defaultImageName];
    
    self.photoImageView.image = nil;
    [self dismissLoading];
//    self.image = nil;
//    self.imgStr = nil;
//    self.imgData = nil;
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    UIView* touchView = [super hitTest:point withEvent:event];
    
    if ([touchView isEqual:self.noPhotoView] || [touchView isEqual:self.havePhotoView]) {
        return self;
    }
    
    return touchView;
}

- (void)loadWebImage:(NSString*)url
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
        UIImage* image = [[UIImage alloc] initWithData:data];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!self.isShotPhoto) {
                self.photoImageView.image = image;
            }
            
//            self.image = image;
//            self.imgData = UIImageJPEGRepresentation(image, 1.0);
            
//            self.imgStr = [Utility toHexString:self.imgData];
            [self dismissLoading];
        });
    });
    [self showLoading];
}

- (void) showLoading
{
    if (!self.loadView) {
        self.loadView = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
        self.loadView.center = self.noPhotoView.center;
        [self addSubview:self.loadView];
    }
    [self.loadView startAnimating];
}

- (void) dismissLoading
{
    if (self.loadView) {
        [self.loadView stopAnimating];
        [self.loadView removeFromSuperview];
        self.loadView = nil;
    }
}


- (void)setMsg:(NSString*)msg imageName:(NSString*)imageName status:(PhotoStatus)status helpImageName:(NSString*)helpImageName{
    [self setMsg:msg imageName:imageName status:status helpImageName:helpImageName url:nil];
}

- (void)setMsg:(NSString*)msg imageName:(NSString*)imageName status:(PhotoStatus)status helpImageName:(NSString*)helpImageName url:(NSString*)url{
    self.buttonStatus = status;
    self.msgLabel.text = msg;
    self.helpImage = [UIImage imageNamed:helpImageName];
    [self.msgLabel sizeToFit];
    self.msgLabel.center = CGPointMake(self.frame.size.width / 2, self.msgLabel.center.y);
    
    CGRect tagFrame = self.tagLabel.frame;
    tagFrame.origin.x = self.msgLabel.frame.origin.x - tagFrame.size.width;
    self.tagLabel.frame = tagFrame;
    self.defaultImageName = imageName;
    
    if (msg) {
        NSRange range = [msg rangeOfString:@"营业执照"];
        if (range.length != 0) {
            self.tagLabel.hidden = YES;
        }
    }
    UIImage* image = nil;
    if (status == PhotoStatusNotSubmit) {
        image = [UIImage imageNamed:imageName];
        self.tagImageView.image = image;
    }else{
        [self loadWebImage:url];
        self.havePhotoView.hidden = NO;
        self.noPhotoView.hidden = YES;
        UIButton* clearButton = (UIButton*)[self.havePhotoView viewWithTag:kClearButtonTag];
        clearButton.userInteractionEnabled = NO;
        [clearButton setImage:[UIImage imageNamed:status == PhotoStatusFailed ? @"warn.png" : @"success.png"] forState:UIControlStateNormal];
        
//        if (status == PhotoStatusSuccess) {
//            self.openCameraButton.hidden = YES;
//        }
    }
    
    CGSize imgSize = CGSizeMake(70, 50);
    self.tagImageView.frame = CGRectMake((self.frame.size.width - imgSize.width) / 2, (self.frame.size.height - imgSize.height) / 2 - 10, imgSize.width, imgSize.height);
    
    CGRect tagImageViewFrame = self.tagImageView.frame;
    CGRect cameraFrame = self.openCameraButton.frame;
    self.openCameraButton.frame = CGRectMake(tagImageViewFrame.origin.x + tagImageViewFrame.size.width - cameraFrame.size.width / 2 + 5,
                                        tagImageViewFrame.origin.y + tagImageViewFrame.size.height - cameraFrame.size.height / 2 + 5,
                                        cameraFrame.size.width,
                                        cameraFrame.size.height);
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)awakeFromNib{
    [self initialize];
}

//- (void)setViewController:(UIViewController*)screen{
//    self.presentScreen = screen;
//    [self addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
//}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage* img = [info objectForKey:UIImagePickerControllerOriginalImage];
    
//    self.image = [img reSize:CGSizeMake(img.size.width / 2, img.size.height / 2)];
//
//    self.imgData = UIImageJPEGRepresentation(self.image, 0);
//    
//    self.imgStr = [Utility toHexString:self.imgData];
    
//    if (self.delegate && [self.delegate respondsToSelector:@selector(photoComplete:withImage:imgStr:)]) {
//        [self.delegate photoComplete:self withImage:self.image imgStr:self.imgStr];
//    }
    
    self.photoImageView.image = [img reSize:CGSizeMake(img.size.width / 2, img.size.height / 2)];
    self.isShotPhoto = YES;
    [self dismissLoading];
    self.havePhotoView.hidden = NO;
    self.openCameraButton.hidden = YES;
    self.noPhotoView.hidden = YES;
    
    UIButton* clearButton = (UIButton*)[self.havePhotoView viewWithTag:kClearButtonTag];
    clearButton.userInteractionEnabled = YES;
    [clearButton setImage:[UIImage imageNamed:@"clear.png"] forState:UIControlStateNormal];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc{
    self.tagLabel = nil;
    self.msgLabel = nil;
    self.tagImageView = nil;
    self.noPhotoView = nil;
    self.havePhotoView = nil;
    self.openCameraButton = nil;
    self.photoImageView = nil;
    self.defaultImageName = nil;
    self.helpImage = nil;
    
    self.delegate = nil;
    self.presentScreen = nil;
    self.loadView = nil;
    
    [super dealloc];
}
@end
